package TableEditions;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.main;
import Tables.ProductTableInterface;
import Utility.JTextFieldFilter;
import Utility.Product;

public class ProductEdition extends JFrame {
	
    private JTextField productCodeTextField = new JTextField();
    private JTextField buyingPriceTextField = new JTextField();
    private JTextField sellingPriceTextField = new JTextField();
    private JTextField productNameTextField = new JTextField();
    private JComboBox supplierCodeCombo;
    
    int[] supplierCode;
  
    
    public Product productToAdd= new Product();
    boolean productCodeFlag=true;
    boolean productNameFlag=true;
    boolean productBuyingPriceFlag=true;
    boolean productSellingPriceFlag=true;
    boolean productSupplierCodeFlag=true;
    int selectedSupplierIndex=0;
    
	
	
	
    private JButton productEditButton;
    ProductTableInterface cti;
 
    public ProductEdition(final ProductTableInterface cti,Product product) {
		super("Ürün Düzenleme Ekranı");
		setTitle("Ürün Düzenleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel codeLabel = new JLabel("Ürün Kodu");
		codeLabel.setBounds(20, 10, 90, 20);
		getContentPane().add(codeLabel);
		
		productToAdd=product;
		
		productCodeTextField = new JTextField();
		productCodeTextField.setText(product.getProductCode());
		productCodeTextField.setEditable(false);
		productCodeTextField.setBounds(124, 11, 115, 20);
		getContentPane().add(productCodeTextField);
		productCodeTextField.setColumns(10);
		
		JLabel buyingPriceLabel = new JLabel("Alış Fiyatı");
		buyingPriceLabel.setBounds(20, 40, 90, 20);
		getContentPane().add(buyingPriceLabel);
		
		buyingPriceTextField = new JTextField();
		buyingPriceTextField.setText(Float.toString(product.getProductBuyingPrice()));
		buyingPriceTextField.setBounds(124, 43, 115, 20);
		//buyingPriceTextField.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));
		getContentPane().add(buyingPriceTextField);
		buyingPriceTextField.setColumns(10);
		
		sellingPriceTextField = new JTextField();
		sellingPriceTextField.setBounds(370, 43, 114, 19);
		sellingPriceTextField.setText(Float.toString(product.getProductSellingPrice()));
		//sellingPriceTextField.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));
		getContentPane().add(sellingPriceTextField);
		sellingPriceTextField.setColumns(10);
		
		
		JLabel sellingPriceLabel = new JLabel("Satış Fiyatı");
		sellingPriceLabel.setBounds(270, 40, 90, 20);
		getContentPane().add(sellingPriceLabel);
		
		JLabel nameLabel = new JLabel("Ürün Adı");
		nameLabel.setBounds(270, 10, 90, 20);
		getContentPane().add(nameLabel);
		
		productNameTextField = new JTextField();
		productNameTextField.setText(product.getProductName());
		productNameTextField.setBounds(370, 10, 115, 20);
		getContentPane().add(productNameTextField);
		productNameTextField.setColumns(10);
		
		
		supplierCodeCombo = new JComboBox();
		supplierCodeCombo.setBounds(124, 70, 115, 20);
		getContentPane().add(supplierCodeCombo);
		   try {
			   Connection conn = null;
		        Statement stmt = null;
		        ResultSet rss = null;

		        String url = "jdbc:mysql://localhost:3306/mydb";
		        String user = "root";
		        String password = "qweasdzxc";
		        
		        conn = (Connection) DriverManager.getConnection(url, user, password);
				stmt = (Statement) conn.createStatement();
				rss=stmt.executeQuery("SELECT * from supplier WHERE activity='1'");
				
				int counter=0;
				while(rss.next()){
					counter++;
					
				}
				int m=0;
				if(counter!=0){
				rss.first();
				supplierCode= new int[counter];
				
				
				}


					
					
					rss=stmt.executeQuery("SELECT * from supplier WHERE activity='1'");
					
					int counter2=0;
					while(rss.next()){
						counter2++;
						
					}
					if(counter2!=0){
						rss.first();
					
					m=0;	
					supplierCodeCombo.addItem(rss.getString("supplier_code"));
					
					//supplierCode[m]=rss.getInt("product_supplier_code");
					m++;
					if(product.getProductSupplierCode().equals(rss.getString("supplier_code"))){
						selectedSupplierIndex=m-1;
					}
					
				
					
				
					while(rss.next()){
						//vehicleId[m]=rss.getInt("vehicle_id");
						supplierCodeCombo.addItem(rss.getString("supplier_code"));
						m++;
						if(product.getProductSupplierCode().equals(rss.getString("supplier_code"))){
							selectedSupplierIndex=m-1;
						}
					}
					}
					
					supplierCodeCombo.setSelectedIndex(selectedSupplierIndex);
					
					supplierCodeCombo.addActionListener(new ActionListener() {

						@Override
						public void actionPerformed(ActionEvent event) {
							// TODO Auto-generated method stub
							
							JComboBox comboBox = (JComboBox) event.getSource();
						     
		                    //
		                    // Print the selected items and the action command.
		                    //
		                    Object selected = comboBox.getSelectedItem();
		                    System.out.println("Selected Item  = " + selected);
		                    String command = event.getActionCommand();
		                    System.out.println("Action Command = " + command);
		                    
		                    if(selected.equals("Satıcı Kodu")){
		                    	productSupplierCodeFlag=false;
		                    }else{
		                    	productSupplierCodeFlag=true;
		                    	productToAdd.setProductSupplierCode(selected.toString());
		                    }
		                    
							
							
						}
						
					});
				
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		JLabel supplierCodeLabel = new JLabel("Satıcı Kodu");
		supplierCodeLabel.setBounds(20, 70, 90, 20);
		getContentPane().add(supplierCodeLabel);
		
	
		productToAdd.setProductSellingPrice(Float.parseFloat(sellingPriceTextField.getText()));
		
		buyingPriceTextField.getDocument().addDocumentListener(new DocumentListener() {
  			
			@Override
			public void removeUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductBuyingPrice(Float.parseFloat(buyingPriceTextField.getText()));
					productBuyingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductBuyingPrice(0);
					productBuyingPriceFlag=false;
				}
			}
			
			@Override
			public void insertUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductBuyingPrice(Float.parseFloat(buyingPriceTextField.getText()));
					productBuyingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductBuyingPrice(0);
					productBuyingPriceFlag=false;
				}
				}
			
			@Override
			public void changedUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductBuyingPrice(Float.parseFloat(buyingPriceTextField.getText()));
					productBuyingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductBuyingPrice(0);
					productBuyingPriceFlag=false;
				}
				
			}
		});
  
		productToAdd.setProductSellingPrice(Float.parseFloat(sellingPriceTextField.getText()));
		
		sellingPriceTextField.getDocument().addDocumentListener(new DocumentListener() {
  			
			@Override
			public void removeUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductSellingPrice(Float.parseFloat(sellingPriceTextField.getText()));
					productSellingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductSellingPrice(0);
					productSellingPriceFlag=false;
				}
			}
			
			@Override
			public void insertUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductSellingPrice(Float.parseFloat(sellingPriceTextField.getText()));
					productSellingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductSellingPrice(0);
					productSellingPriceFlag=false;
				}
				}
			
			@Override
			public void changedUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				try{
					productToAdd.setProductSellingPrice(Float.parseFloat(sellingPriceTextField.getText()));
					productSellingPriceFlag=true;
				}catch(NumberFormatException e){
					productToAdd.setProductSellingPrice(0);
					productSellingPriceFlag=false;
				}
			}
		});
  
  
  
		
		
		
		
		
		productEditButton = new JButton("Düzenle");
		productEditButton.setForeground(Color.BLACK);
		productEditButton.setFont(new Font("Arial", Font.BOLD, 16));
		productEditButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			    
				
				productToAdd.setProductCode(productCodeTextField.getText());
				if(productToAdd.getProductCode().equals("")){
					productCodeFlag=false;
				}
				else{
					productCodeFlag=true;
				}
				
				productToAdd.setProductName(productNameTextField.getText());
				if(productToAdd.getProductName().equals("")){
					productNameFlag=false;
				}
				else{
					productNameFlag=true;
				}
				
				//productToAdd.setProductBuyingPrice(Float.parseFloat(buyingPriceTextField.getText()));
				System.out.println("productBuyingPrice= "+productToAdd.getProductBuyingPrice());
				System.out.println("productSellingPrice= "+productToAdd.getProductSellingPrice());
				
				if(productToAdd.getProductBuyingPrice()!=0){
					productBuyingPriceFlag=true;
				}
				else{
					productBuyingPriceFlag=false;
				}
				
				if(productToAdd.getProductSellingPrice()!=0){
					productSellingPriceFlag=true;
				}
				else{
					productSellingPriceFlag=false;
				}
				
				
				
				System.out.println("Code flag="+productCodeFlag);
				System.out.println("Name flag="+productNameFlag);
				System.out.println("Buying Price flag="+productBuyingPriceFlag);
				System.out.println("Selling Price flag="+productSellingPriceFlag);
				System.out.println("Supplier Code flag="+productSupplierCodeFlag);
				
				
				
	
				if(productCodeFlag && productNameFlag && productBuyingPriceFlag 
						&& productSellingPriceFlag && productSupplierCodeFlag){
			
			
				System.out.println("Ready to add product");
				 	Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";

			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate("UPDATE product SET product_name='"+productToAdd.getProductName()+"',product_supplier_code='"+productToAdd.getProductSupplierCode()+"'," +
			            		"product_buying_price='"+productToAdd.getProductBuyingPrice()+"',product_selling_price='"+productToAdd.getProductSellingPrice()+"' WHERE product_code='"+productToAdd.getProductCode()+"'");
			         //   st.executeUpdate("UPDATE customer SET customer_phone='0554755' WHERE customer_name='rehber';");
			            int messageType = JOptionPane.PLAIN_MESSAGE;
			            JOptionPane.showMessageDialog(null, "Güncelleme Yapıldı", "Uyarı!!", messageType);
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
			        
				
			        
			        // this will make sure WindowListener.windowClosing() et al. will be called.
			      //  WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
			        //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

			        // this will hide and dispose the frame, so that the application quits by
			        // itself if there is nothing else around. 
			        cti.addNewItem();
			        setVisible(false);
			        dispose();
			        
				}
			}});
		
		productEditButton.setBounds(385, 102, 120, 30);
		getContentPane().add(productEditButton);
		
		
		
	setVisible(true);  
		
	}
}
